<?php

include_once (__DIR__ . '/../dao/globalZoneDao.php');
include_once (__DIR__ . '/../utils/requestUtils.php');

class GlobalZoneServices {

    public function __construct() {
        
    }

    function create($operator, $zone) {
        $connection = new DBConnection();
        $connection->connect();
        $dao = new GlobalZoneDao($connection);
        $r = $dao->create(
                $operator, escapeInput($connection->getConnection(), $zone));
        $connection->close();
        return $r;
    }

    function getZonesByOperator($operator) {
        $connection = new DBConnection();
        $connection->connect();
        $dao = new GlobalZoneDao($connection);
        $r = $dao->getZoneByOperator($operator);
        $connection->close();
        return $r;
    }

    function insidePolygon($v, $points) {
        $p = $points[0];
        $q = $points[1]; 
        $sign0 = $this->pvq($p, $v, $q);
        for ($index = 1; $index < count($points) - 1; $index++) {
            $p = $points[$index];
            $q = $points[$index + 1];
            $sign1 = $this->pvq($p, $v, $q);
            // echo toString($p).' '.toString($v).' '.toString($q).' -> '.$sign1.'           ';
            // echo $sign0.' vs '.$sign1.'<br>';
            if ($sign1 == 0) {
                // le point appartient à la ligne
                return true;
            }
            if ($sign0 + $sign1 == 0) {
                // changement de signe
                return false;
            }
            $sign0 = $sign1;
        }
        return true;
    }

    private function pvq($p, $v, $q) { 
        $t = ($q->lng - $p->lng) * ($v['lat'] - $p->lat) - ($v['lng'] - $p->lng) * ($q->lat - $p->lat);
        if ($t < 0)
            return -1;
        if ($t == 0)
            return 0;
        if ($t > 0)
            return 1;
    }

}

/**
 * IsInside
 */
function test() {
    $ps = [];

    $ps[0] = pt(2, 7);
    $ps[1] = pt(7, 10);
    $ps[2] = pt(12, 6);
    $ps[3] = pt(9, 1);
    $ps[4] = pt(3, 3);
    $ps[5] = pt(2, 7);


    for ($x = 0; $x < 12; $x++) {
        $v = pt($x, 12 - $x);
        if (isInsidePolygon($v, $ps) == true) {
            echo 'OUI ' . toString($v) . '<br>';
        } else {
            echo 'NON ' . toString($v) . '<br>';
        }
    }
}

function pt($lng, $lat) {
    $r = [];
    $r['lng'] = $lng;
    $r['lat'] = $lat;
    return $r;
}

/*
 * Retourn vrai, si le point $v est dand le polygone $points
 */

function toString($p) {
    return '(' . $p['lng'] . '-' . $p['lat'] . ')';
}
